package com.csbaic.web;

import com.csbaic.web.advice.ExceptionAdvice;
import com.csbaic.web.advice.ResultBodyAdvice;
import com.csbaic.web.interceptor.ResponseResultInterceptor;
import com.csbaic.web.jackson.LocalDateTimeToLongSerializer;
import com.csbaic.web.jackson.LongToLocalDateTimeDeserializer;
import com.fasterxml.jackson.annotation.JsonInclude;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.time.LocalDateTime;

@Configuration
public class SimpleWebMvcConfigurer implements WebMvcConfigurer {

    @Bean
    public ExceptionAdvice exceptionAdvice(){
        return new ExceptionAdvice();
    }

    @Bean
    public ResultBodyAdvice resultBodyAdvice(){
        return new ResultBodyAdvice();
    }



    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new ResponseResultInterceptor());
    }

    @Bean
    public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer(){
        return new Jackson2ObjectMapperBuilderCustomizer() {
            @Override
            public void customize(Jackson2ObjectMapperBuilder jacksonObjectMapperBuilder) {
                jacksonObjectMapperBuilder.serializationInclusion(JsonInclude.Include.NON_NULL);
                jacksonObjectMapperBuilder.failOnEmptyBeans(false);
                jacksonObjectMapperBuilder.failOnUnknownProperties(false);
//                jacksonObjectMapperBuilder.simpleDateFormat("yyyyMMddHHmmss");

                jacksonObjectMapperBuilder.serializerByType(LocalDateTime .class, new LocalDateTimeToLongSerializer());
                jacksonObjectMapperBuilder.deserializerByType(LocalDateTime.class, new LongToLocalDateTimeDeserializer());
            }
        };
    }
}
